//
//  MainViewController.swift
//  OnemeetingDemo
//
//  Created by zhangheng on 2019/11/18.
//  Copyright © 2019 www.onemeeting.1meetingIos. All rights reserved.
//

import Foundation


class MainViewController: NSViewController {
    
    let images = ["ic_settings","ic_share","ic_lang_en","ic_refresh","icon_login_smart"]
    let bottomTitles = ["技术支持","使用说明","关于我们","检查更新"]
    
    override func loadView() {
        let view = NSView.init(frame: NSMakeRect(0, 0, kWindowWidth, kWindowHeight))
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.white.cgColor
        self.view = view
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.sdkAuto()
        self.setupUI()
        self.loadData()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewWillAppear() {
        super.viewWillAppear()
        
        //登录状态
        NotificationCenter.default.addObserver(self, selector: #selector(loginStatus(notification:)), name: MTLoginStateNotification, object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(doMeetingNot(not:)), name: MTDoMeetingNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(settingsChangeNot(not:)), name: MTSetChangeNotification, object: nil)
    }
    
    func setupUI() -> () {
        
        self.view.addSubview(leftView)
        leftView.snp.makeConstraints { (make) in
            make.width.equalTo(kLeftWidth)
            make.left.top.bottom.equalToSuperview()
        }
        
        self.view.addSubview(rightView)
        rightView.snp.makeConstraints { (make) in
            make.width.equalTo(kRightWidth)
            make.right.top.bottom.equalToSuperview()
        }
        
        self.leftView.addSubview(logoImgV)
        logoImgV.snp.makeConstraints { (make) in
            make.width.height.equalTo(kLogoX)
            make.centerX.equalToSuperview()
            make.top.equalTo(90)
        }

        self.leftView.addSubview(logoLabImgV)
        logoLabImgV.snp.makeConstraints { (make) in
            make.width.equalTo(kLogo_LabWidth)
            make.height.equalTo(kLogo_LabHeight)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-60)
        }
        
        
        self.rightView.addSubview(hostView)
        hostView.snp.makeConstraints { (make) in
            make.width.equalTo(300)
            make.height.equalTo(44)
            make.centerX.equalToSuperview()
            make.top.equalTo(90)
        }
        
        self.rightView.addSubview(joinView)
        joinView.snp.makeConstraints { (make) in
            make.width.equalTo(300)
            make.height.equalTo(44)
            make.centerX.equalToSuperview()
            make.top.equalTo(hostView.snp.bottom).offset(30)
        }
        
        
        self.view.addSubview(topView)
        topView.snp.makeConstraints { (make) in
            make.width.equalTo((kIconDefault+15)*CGFloat(images.count))
            make.height.equalTo(kIconDefault)
            make.right.equalTo(-5)
            make.top.equalToSuperview().offset(10)
        }
        self.initTop()
        
        
        self.rightView.addSubview(bottomView)
        bottomView.snp.makeConstraints { (make) in
            make.left.equalTo(30)
            make.right.equalTo(30)
            make.height.equalTo(20)
            make.bottom.equalTo(-50)
        }
        self.initBottomTitles()
        
        self.rightView.addSubview(verLab)
        verLab.snp.makeConstraints { (make) in
            make.width.equalTo(100)
            make.height.equalTo(20)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-10)
        }
        
        self.rightView.addSubview(proView)
        proView.snp.makeConstraints { (make) in
            make.width.equalTo(100)
            make.height.equalTo(24)
            make.top.equalTo(8)
            make.right.equalTo(topView.snp.left).offset(-10)
        }
        
        self.leftView.addSubview(resetBtn)
        resetBtn.snp.makeConstraints { (make) in
            make.width.height.equalTo(20)
            make.bottom.equalToSuperview()
            make.left.equalToSuperview()
        }
    }
    
    lazy var appDelegate: AppDelegate = {
        return (NSApplication.shared.delegate as! AppDelegate)
    }()
    
    lazy var proView: ProView = {
        let view = ProView.init(frame: NSRect.zero)
        view.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.2).cgColor
        view.wantsLayer = true
        view.tapDelegate = self
        return view
    }()
    
    lazy var bottomView: NSView = {
        let view = NSView()
        return view
    }()
    
    func initBottomTitles()  {
        var keyTitls = [NSTextField]()
        let btnwidth = 90
        let spacing = ((kRightWidth-60)-CGFloat(bottomTitles.count*btnwidth))/CGFloat(bottomTitles.count-1)
        for (i,value) in bottomTitles.enumerated() {
            let title = HyTextF()
            title.setLabel(title: value, textColor: color_main140, font: NSFont.systemFont(ofSize: 13))
            title.attributedStringValue =  NSAttributedString.hyperlinkFromString(inString: value,textColor: color_main140)
            title.tag = 100+i
            title.addTouchBlock { (text,count) in
                self.buttomTefAction(senber: title)
            }
            
            title.alignment = .center
            title.sizeToFit()
            bottomView.addSubview(title)
            keyTitls.append(title)
            title.snp.makeConstraints { (make) in
                make.width.equalTo(btnwidth)
                make.centerY.equalToSuperview()
                make.height.equalTo(20)
                if i == 0 {
                    make.left.equalTo(0)
                }else {
                    make.left.equalTo(keyTitls[i-1].snp.right).offset(spacing)
                }
            }
        }
    }
    
    func butomTxtReloadUI() {
       for (i,value) in bottomTitles.enumerated() {
            let tX = self.bottomView.viewWithTag(100+i) as! HyTextF
            tX.stringValue = value.localized()
        }
    }
    
    @objc func buttomTefAction(senber:NSTextField) -> () {
        if RtcEngine.isNoData() == true {
            return
        }
        
        switch senber.tag {
        case 100:
            let pam:[String:Any] = ["number":mt_ID_SEVICE,"username":UserInfoManager.shared.ownid ?? "未知"]
            RtcEngine.responseDataJoinAndDoAndHost(parmas: pam, success: nil)
        case 101:
            NSWorkspace.shared.open(NSURL(string:mt_url_besc)! as URL)
        case 102:
            NSWorkspace.shared.open(NSURL(string:mt_url_about)! as URL)
        case 103:
            NetVersion.checkComp { (isok,res) in
                if isok {
                    NetVersion.versionCompUpdate()
                }else {
                    let window = BaseWindow()
                    window.contentViewController = VersionController()
                    let windowC = NSWindowController()
                    windowC.window = window
                    windowC.window?.orderFront(nil)
                }
            }
        default:
            break
        }
    }
    
    lazy var topView: NSView = {
        let view = NSView()
        return view
    }()
    
    func initTop() {
        let spacing = CGFloat(15)
        for (inx,val) in images.enumerated() {
            let btn = LLCustomBtn()
            btn.defaultBackgroundImage = NSImage.init(named: NSImage.Name.init(val))
            btn.isHandCursor = true
            btn.action = #selector(topBtnsAction(senber:))
            btn.target = self
            btn.tag = 1000+inx
            self.topView.addSubview(btn)
            btn.snp.makeConstraints { (make) in
                make.width.height.equalTo(kIconDefault)
                make.right.equalTo(-8-CGFloat(inx)*(kIconDefault+spacing))
                make.centerY.equalToSuperview()
            }
        }
    }
    
    @objc func topBtnsAction(senber:LLCustomBtn)  {
        
        switch senber.tag {
        case 1000:
            if RtcEngine.isNoData() == true {
                return
            }
            
            let window = BaseWindow()
            window.contentViewController = SetViewContrller()
            let windowC = NSWindowController()
            windowC.window = window
            windowC.window?.orderFront(nil)
            
        case 1001:
            /*
            if RtcEngine.isNoData() == true {
                return
            }
            
            let window = BaseWindow()
            window.contentViewController = QRViewController.init(url: URL.init(string: "http://www.1meeting.cn/articledetail?aid=666")!)
            let windowC = NSWindowController()
            windowC.window = window
            windowC.window?.orderFront(nil)
            */
            
            let window = BaseWindow()
            window.contentViewController = ShareViewController()
            let windowC = NSWindowController()
            windowC.window = window
            windowC.window?.orderFront(nil)
        case 1002:
            let lang = UserInfoManager.shared.lang == "zh-Hans" ? "en":"zh-Hans"
            UserInfoManager.shared.lang = lang
            self.lang = UserInfoManager.shared.lang!
            
            let info = InfokDialog.init(title: "语言设置".localized(),contText: "语言设置成功，部分功能需要重启".localized(),btnTitle: "立即重启".localized(),twoBtnTitle: "取消".localized(),image: NSImage.imageNamed("logo_128"))
            let dia = KDialog.shared
            dia.tapBlock = { index in
                if index == 0 {
                    //ZH.delegate()?.relaunchApp()
                    XQProcess.restart()
                }else {
                    dia.close()
                }
            }
            dia.runModal(info: info)
            
        case 1003:
            self.reLoadData(success: nil)
        case 1004:
            if UserInfoManager.shared.isLogin==true {
                Dialog.shared.show(title: "注销账号".localized(), msg: "你确定退出登录了吗".localized(), confirmBtnTitle: "退出".localized(), confirmAction: { (senber) in
                    UserInfoManager.shared.isLogin = false
                    UserInfoManager.shared.memid = nil
                    UserInfoManager.shared.checkCode = nil
                    NotificationCenter.default.post(name: MTLoginStateNotification, object: nil)
                }, cacalBtnTitle: "取消".localized(), cacalAction: nil)
                
            }else {
                let window = LoginWindow.shared
                window.contentViewController = LoginViewController()
                let windowC = NSWindowController()
                windowC.window = window
                windowC.window?.orderFront(nil)
            }
        default:
            break
        }
    }
    
    lazy var leftView: NSView = {
        let view = NSView()
        view.wantsLayer = true
        view.layer?.backgroundColor = color_main140.cgColor
        return view
    }()
    
    lazy var rightView: NSView = {
        let view = NSView()
        view.wantsLayer = true
        view.layer?.backgroundColor = color_gray(238).cgColor
        return view
    }()
    
    lazy var logoImgV: NSImageView = {
        let imageV = NSImageView.init()
        imageV.wantsLayer = true
        imageV.image = NSImage.init(named: NSImage.Name.init("ic_logo"))
        imageV.layer?.cornerRadius = kLogoX/2
        imageV.layer?.masksToBounds = true
        return imageV
    }()
    
    lazy var logoLabImgV: NSImageView = {
        let imageV = NSImageView.init()
        imageV.image = NSImage.init(named: NSImage.Name.init("ic_logo_lab".localized()))
        return imageV
    }()
    
    lazy var hostView: MTView = {
        let view = MTView.init(frame: CGRect.zero)
        view.wantsLayer = true
        view.layer?.backgroundColor = color_main140.cgColor
        view.layer?.borderColor = NSColor.clear.cgColor
        view.layer?.borderWidth = 0
        view.layer?.masksToBounds = true
        view.layer?.cornerRadius = 0
        view.defLab.textColor = NSColor.white
        view.defLab.stringValue = "主持会议".localized()
        view.lineV.layer?.backgroundColor = NSColor.white.cgColor
        view.defBtn.action = #selector(hostBtnAction)
        view.defBtn.target = self
        return view
    }()
    
    lazy var joinView: MTView = {
        let view = MTView.init(frame: CGRect.zero)
        view.wantsLayer = true
        view.layer?.backgroundColor = color_gray(238).cgColor
        view.layer?.borderColor = color_gray(200).cgColor
        view.layer?.borderWidth = 1
        view.layer?.masksToBounds = true
        view.layer?.cornerRadius = 0
        view.defLab.textColor = NSColor.black
        view.defLab.stringValue = "参加会议"
        view.defaulTef.cell?.title = ""
        view.defaulTef.placeholderString = "请输入会议号"
        view.defaulTef.focusRingType = NSFocusRingType.none
        view.defBtn.action = #selector(joinBtnAction)
        view.defBtn.target = self
        view.lineV.layer?.backgroundColor = color_gray(200).cgColor
        view.defaulTef.cell?.isEditable = true
        view.defaulTef.textColor = NSColor.black
        return view
    }()
    
    lazy var resetBtn: ZHButton = {
        let btn = ZHButton.init(frame: NSRect.zero)
        btn.zh_title = "nihao"
        btn.target = self
        btn.action = #selector(resetBtnAction(senber:))
        return btn
    }()
    
    lazy var verLab: NSTextField = {
        let lab = NSTextField.label(title: "V 1.0", textColor: color_gray(120), font: NSFont.systemFont(ofSize: 12))
        lab.alignment = .center
        return lab
    }()
    
    lazy var inputV: InputNameView = {
        let view = InputNameView.init(frame: NSRect.init(x: 0, y: 0, width: 0, height: 160))
        return view
    }()
  
    
    func inputName(complete:(()->())? = nil,
           cancal:(()->())? = nil) {
        if UserInfoManager.shared.disname == "壹会通" ||
        UserInfoManager.shared.disname == nil ||
            UserInfoManager.shared.disname == "" {
            self.inputV.cacalBtn.defaultTitle = "取消".localized()
            self.inputV.canfirmBtn.defaultTitle = "确定".localized()
            self.inputV.formLab.stringValue = "(仅支持中文，英文，数字，11位以内)".localized()
            self.inputV.tef.defaulTef.placeholderString = "请输入".localized()
            Dialog.shared.initlize("设置名称".localized())
            Dialog.shared.diaWidth = CGFloat(400)
            Dialog.shared.addCont(view: self.inputV, height: 150)
            Dialog.shared.show(inView: nil)
            complete!()
        }else {
            cancal!()
        }
    }
    
   
    @objc func hostBtnAction() -> () {
        if RtcEngine.isNoData() == true {
            return
        }
        
        var mData = MBefineData()
        mData.roomid = self.hostView.defaulTef.stringValue
        mData.username = UserInfoManager.shared.disname
        mData.password = UserInfoManager.shared.kPassword
        mData.isJoin = false
        NotificationCenter.default.post(name: MTDoMeetingNotification, object: mData)
        
    }
    
    @objc func joinBtnAction() -> () {
        
        if RtcEngine.isNoData() == true {
            return
        }
        
        
        let number = self.joinView.defaulTef.stringValue
        if number.count <= 1 {
            return
        }
        
        var mData = MBefineData()
        mData.roomid = number
        mData.username = UserInfoManager.shared.disname
        mData.isJoin = true
        NotificationCenter.default.post(name: MTDoMeetingNotification, object: mData)
        
    }
    
    
    var lang:String = "zh-Hans" {
        didSet{
            
            //核心
            Localize.setCurrentLanguage(lang)
            
            //底部菜单刷新
            self.butomTxtReloadUI()
            
            //输入框刷新
            self.hostView.defLab.stringValue = "主持会议".localized()
            self.joinView.defLab.stringValue = "加入会议".localized()
            self.joinView.defaulTef.placeholderString = "请输入会议号".localized()
            
            //logo文字
            self.logoLabImgV.image = NSImage.init(named: NSImage.Name.init("ic_logo_lab".localized()))
            
            //右上角按钮变化
            let name = lang == "zh-Hans" ? "en":"zh-Hans"
            let btn = (self.topView.viewWithTag(1002) as? LLCustomBtn)
            btn?.defaultBackgroundImage = NSImage.init(named: NSImage.Name.init("ic_lang_"+name))
            
            //付费按钮
            guard let time = UserInfoManager.shared.time else {
                return
            }
            self.proView.reloadTime(oldtime:time)
            
        }
    }
    
    func loadData() {
        self.LocalRefreshData()
        self.verLab.stringValue = "V "+AppInfo.majorVersion()
        if UserInfoManager.shared.lang != nil {
            self.lang = UserInfoManager.shared.lang!
        }
        self.appDelegate.urlDelegate = self
    }
    
    func sdkAuto() {
        //ZoomsdkManger.shared.sdkAuth(false)
    }
    
    func LocalRefreshData() {
        if RtcEngine.noData() == false{
            var dataDic:[String:Any] = [:]
            dataDic["time"] = UserInfoManager.shared.time
            dataDic["ownid"] = UserInfoManager.shared.ownid
            self.setDataUI(result: dataDic)
        }else {
            self.reLoadData(success: nil)
        }
    }
    
    func setDataUI(result:[String:Any]) {
        
        guard let time = result["time"] as? String,let ownid = result["ownid"] as? String else {
            return
        }
        self.hostView.defaulTef.stringValue = ownid
        self.proView.reloadTime(oldtime: time)
        
        //头像
        if UserInfoManager.shared.isLogin == true {
            guard let photo = UserInfoManager.shared.photo,UserInfoManager.shared.photo != "" else {
                self.logoImgV.image = NSImage.imageNamed("icon_logo_noPhoto")
                self.reLoadData(success: nil)
                return
            }
            self.logoImgV.sd_setImage(with: URL.init(string: photo), completed: nil)
        }else {
            self.logoImgV.image = NSImage.imageNamed("ic_logo")
        }
    }
    
    
    
    func reLoadData(success:(([String:AnyObject])->())?=nil) {
        HUD.show()
        RtcEngine.responseDataHost { (result) in
            HUD.dismiss()
            self.modeDataUI(result: result)
            if success != nil {
                success!(result)
            }
        }
        
    }
    
    func modeDataUI(result:[String:AnyObject]) {
        var dataDic:[String:Any] = [:]
        if UserInfoManager.shared.isLogin == true {
            let mode = SJMemMode.deserialize(from: result)
            dataDic["time"] = mode?.data?.time
            dataDic["ownid"] = mode?.data?.ownid
        }else {
            let mode = SJMeetingMode.deserialize(from: result)
            dataDic["time"] = mode?.time
            dataDic["ownid"] = mode?.ownid
        }
        self.setDataUI(result: dataDic)
    }
    
    @objc func resetBtnAction(senber:ZHButton) {
        Dialog.shared.show(title: "重设会议号".localized(), msg: "会销毁当前软件所有数据，重新获取号码，请谨慎此操作".localized(), confirmBtnTitle: "重启".localized(), confirmAction: { (senber) in
            UserInfoManager.shared.removeForKey(key: "USER_ownidKey")
            UserInfoManager.shared.removeForKey(key: "USER_ownid")
            UserInfoManager.shared.removeForKey(key: "USER_time_g")
            UserInfoManager.shared.removeForKey(key: "USER_time")
            UserInfoManager.shared.removeForKey(key: "USER_hostId")
            UserInfoManager.shared.removeForKey(key: "USER_token")
            UserInfoManager.shared.removeForKey(key: "USER_zak")
            UserInfoManager.shared.removeForKey(key: "USER_disname")
            UserInfoManager.shared.removeForKey(key: "USER_isLogin")
            UserInfoManager.shared.removeForKey(key: "USER_ID_memid")
            UserInfoManager.shared.removeForKey(key: "USER_checkCode")
            XQProcess.restart()
        }, cacalBtnTitle: "取消".localized(), cacalAction: nil)
        
        
        
    }
  
}


extension MainViewController:WebSchemaDelegate {
    func onHandleUrl(params:[String:Any]?, type: RtcType) {
        RtcEngine.handurlPatamts(params: params, type: type)
    }
}

extension MainViewController : MSViewDelegate{
    func taped(senber: MSView) {
        if RtcEngine.isNoData() == true {
            return
        }
        
        if UserInfoManager.shared.isLogin==false{
            let window = LoginWindow.shared
            window.contentViewController = LoginViewController()
            let windowC = NSWindowController()
            windowC.window = window
            windowC.window?.orderFront(nil)
        }else {
            let urlString = mt_url_pay+"?ownid=c\(UserInfoManager.shared.ownid!)"
            let window = BaseWindow()
            window.contentViewController = QRPayViewController.init(url: URL.init(string: urlString)!)
            let windowC = NSWindowController()
            windowC.window = window
            windowC.window?.orderFront(nil)
        }
        
    }
    
}



extension MainViewController {
    
    @objc func settingsChangeNot(not:Notification) {
        self.reLoadData(success: nil)
    }
    
    @objc func doMeetingNot(not:Notification) {
        guard let mData = not.object as? MBefineData else {
            return
        }
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+0.4) {
            let window = SharedWindow.shared
            window.contentViewController = JoinViewController.init(data: mData)
            let windowC = NSWindowController()
            windowC.window = window
            windowC.window?.orderFront(nil)
            
        }
    }
    
    
    @objc func loginStatus(notification:Notification) {
        let text = UserInfoManager.shared.isLogin == true ? "登录成功":"退出登录"
        show_msg(text.localized())
        self.reLoadData(success: nil)
    }
}

